﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using System.Text;
using MeTalker.Model;
using MeTalker.BLL;
using MeTalker.Securitys.Cryptography;
using System.Security.Cryptography;
using System.Reflection;
/// <summary>
///HandlerBase 的摘要说明
/// </summary>
public class HandlerBase : IRequiresSessionState
{
    public HttpServerUtility Server { get; private set; }
    public HttpRequest Request { get; private set; }
    public HttpResponse Response { get; private set; }
    public HttpSessionState Session { get; private set; }


    public const string TYPE_USER_LOGOUT = "-1";//请求注销
    public const string TYPE_USER_LOGIN = "1";//请求登录
    public const string TYPE_USER_HEART = "2";//请求心跳
    public const string TYPE_USER_LICENSE = "3";//请求许可
    public const string TYPE_USER_REG = "4";//请求注册

    public const string SUCCESS = "1";//请求注册
    public const string FAIL = "-1";//请求注册
    public const string SYSTEM_FAIL = "-99";
    public const string LOGIN_FAIL = "-100";
    public const string LOGIN_OVER_VALID = "-101";
    public const string LOGIN_USER_EXIST = "-102";
    public const string USER_INACTIVE_ACTIVATE = "-103";
    public const string USER_INVALID = "-104";
    public const string LOGIN_DOUBLE = "-105";
    public const string REG_DOUBLE = "-106";
    public const string USER_EXIST = "-107";
    public const string USER_NOT_EXIST = "-108";
    public static readonly string CONST_FLAG = "jlkl2008";
    public static readonly int LOGIN_FLAG_TIME_OUT = int.Parse(System.Configuration.ConfigurationManager.AppSettings["LoginFlagTimeOut"]);
    // internal AESHelper aes = new AESHelper();

    protected string GetMD5(string sDataIn)
    {
        using (MD5 md5 = new MD5CryptoServiceProvider())
        {
            byte[] bytValue = Encoding.UTF8.GetBytes(sDataIn);
            byte[] bytHash = md5.ComputeHash(bytValue);
            md5.Clear();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytHash.Length; i++)
            {
                sb.Append(bytHash[i].ToString("x2").PadLeft(2, '0'));
            }
            return sb.ToString().ToUpper();
        }
    }

    protected byte[] Decrypt(string type, byte[] b)
    {
        if (type.Equals("2"))
            return new AESHelper().Decrypt(b);
        else if (type.Equals("1"))
            return Encoding.UTF8.GetBytes(new Des().DecryStrHex(Encoding.UTF8.GetString(b), Util.DES_KEY_PASS));
        return null;
    }

    protected string DecryptToString(string type, byte[] b)
    {
        byte[] tmp = Decrypt(type, b);
        if (tmp != null)
        {
            string result =Encoding.UTF8.GetString(tmp);
            if (result.Contains(CONST_FLAG)) {
                return result;
            }
        }
        return "";
    }

    protected string EncryptToString(string type, byte[] b)
    {
        byte[] tmp = Encrypt(type, b);
        if (tmp != null)
            return Encoding.UTF8.GetString(tmp);
        return "";
    }
    protected byte[] Encrypt(string type, byte[] b)
    {
        if (type.Equals("2"))
            return new AESHelper().Encrypt(b);
        else if (type.Equals("1"))
            return Encoding.UTF8.GetBytes(new Des().EncryStrHex(Encoding.UTF8.GetString(b), Util.DES_KEY_PASS));
        return null;
    }

    protected string Base64Tostring(string msg)
    {
        return Encoding.UTF8.GetString(Convert.FromBase64String(msg));
    }

    protected void WriteLicense(MembersMod member)
    {
        try
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<resp_data>");
            sb.Append(string.Format("<UserName>{0}</UserName>", member.UserName));
            sb.Append(string.Format("<Success>{0}</Success>", true));
            sb.AppendFormat("<HDID><![CDATA[{0}]]></HDID>", member.HDID);
            sb.Append(string.Format("<UType>{0}</UType>", member.UserType.Equals("1") ? "正式用户" : "试用"));
            sb.Append(string.Format("<ADate>{0}</ADate>", member.AddDate.ToString("yyyy-MM-dd HH:mm:ss")));
            sb.Append(string.Format("<SDate>{0}</SDate>", member.RegistDate.ToString("yyyy-MM-dd HH:mm:ss")));
            sb.Append(string.Format("<EDate>{0}</EDate>", member.ExpireDate.ToString("yyyy-MM-dd HH:mm:ss")));
            sb.Append(string.Format("<LDate>{0}</LDate>", member.LatestOnline.ToString("yyyy-MM-dd HH:mm:ss")));
            sb.Append(string.Format("<TDays>{0}</TDays>", this.GetDay(member.ExpireDate, member.LatestOnline)));
            sb.Append(string.Format("<SId>{0}</SId>", member.SessionId));
            sb.Append("</resp_data>");
            Write(Encoding.UTF8.GetBytes(sb.ToString()));
        }
        finally
        {
        }
    }

    protected void WriteUserLogin(string datatype, MembersMod member)
    {
        member.SessionId = Session.SessionID;
        member.LatestOnline = DateTime.Now;
        try
        {
            Session["user"] = member;
            StringBuilder sb = new StringBuilder();
            sb.Append("<resp_data>");
            sb.Append(string.Format("<Success>{0}</Success>", true));
            sb.Append(string.Format("<UType>{0}</UType>", member.UserType.Equals("1") ? "正式用户" : "试用"));
            sb.Append(string.Format("<ADate>{0}</ADate>", member.AddDate.ToString("yyyy-MM-dd HH:mm:ss")));
            sb.AppendFormat("<HDID><![CDATA[{0}]]></HDID>", member.HDID);
            sb.Append(string.Format("<SDate>{0}</SDate>", member.RegistDate.ToString("yyyy-MM-dd HH:mm:ss")));
            sb.Append(string.Format("<EDate>{0}</EDate>", member.ExpireDate.ToString("yyyy-MM-dd HH:mm:ss")));
            sb.Append(string.Format("<LDate>{0}</LDate>", member.LatestOnline.ToString("yyyy-MM-dd HH:mm:ss")));
            sb.Append(string.Format("<TDays>{0}</TDays>", this.GetDay(member.ExpireDate, member.LatestOnline)));
            sb.Append(string.Format("<SId>{0}</SId>", member.SessionId));
            //sb.Append(string.Format("<SID>{0}</SID>", SessionId));
            sb.Append("</resp_data>");
            //Write(aes.Encrypt(Encoding.UTF8.GetBytes( sb.ToString())));
            Write(Encrypt(datatype, Encoding.UTF8.GetBytes(sb.ToString())));
        }
        finally
        {
            MembersBLL.UpdateLoginState(member, true);
            SoftwaresMod software = SoftwaresBLL.GetSoftware(member.SoftID);
            LoginLogBLL.Insert(new LoginLogMod() { IpAddress = Request.UserHostAddress, LoginDate = DateTime.Now, SoftName = software != null ? software.SoftName : "", UserName = member.UserName });
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    protected void Init(HttpContext context)
    {
        Request = context.Request;
        Response = context.Response;
        Server = context.Server;
        Session = context.Session;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    protected string GetSessionId(string msg)
    {
        byte[] b = Encoding.UTF8.GetBytes(DateTime.Now.ToString("yyyyMMddHH:mm:ssfff") + msg);
        return Convert.ToBase64String(b, 0, b.Length);
    }
    protected void Write(int intcontent) {
        Write(intcontent.ToString());
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="content"></param>
    protected void Write(string content)
    {
        Response.Write(content);
        HttpContext.Current.ApplicationInstance.CompleteRequest();
        //Response.End();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="content"></param>
    /// <param name="count"></param>
    protected void Write(byte[] content, int count)
    {
        Response.OutputStream.Write(content, 0, count);
        Response.OutputStream.Flush();
        //Response.End();
        HttpContext.Current.ApplicationInstance.CompleteRequest();
    }

    protected void Write(byte[] content)
    {
        Response.OutputStream.Write(content, 0, content != null ? content.Length : 0);
        Response.OutputStream.Flush();
        //Response.End();
        HttpContext.Current.ApplicationInstance.CompleteRequest();
    }

    /// <summary>
    /// 相差的天数
    /// </summary>
    /// <param name="nowTime"></param>
    /// <param name="endTime"></param>
    /// <returns></returns>
    protected int GetDay(DateTime nowTime, DateTime endTime)
    {
        TimeSpan span = nowTime.Subtract(endTime);
        //return span.Days + 1;
        return span.Days;
    }

    /// <summary>
    /// 相差的分钟数
    /// </summary>
    /// <param name="nowTime"></param>
    /// <param name="endTime"></param>
    /// <returns></returns>
    protected double GetMinutes(DateTime nowTime, DateTime endTime)
    {
        return nowTime.Subtract(endTime).TotalMinutes;
        //TimeSpan span = nowTime.Subtract(endTime);
        //return 60 + span.Minutes;
        //return span.Minutes;
    }
}